<template>
  <div class="demo-app">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="步骤一" description="创建用户需先完善基本的账号信息"></el-step>
      <el-step title="步骤二" description="完善用户的个人信息"></el-step>
      <el-step title="步骤三" description="分配用户所属的岗位,和在系统中的角色"></el-step>
      <el-step title="步骤四" description="分配用户可以使用的系统资源"></el-step>
    </el-steps>
    <template v-if="active==0">
      <el-form
        style="margin-top: 30px;"
        ref="userInfoForm"
        :model="models.model"
        :rules="rules.userInfo"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录账号：" prop="loginId">
              <el-input v-model="models.model.loginId"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名：" prop="userName">
              <el-input v-model="models.model.userName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型：" prop="userType">
              <el-select v-model="models.model.userType">
                <el-option
                  v-for="item in controlData.userTypes"
                  :key="item.name"
                  :value="item.name"
                  :label="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="选择部门：" prop="departmentId">
              <!-- <el-cascader
                v-model="models.model.departmentId"
                clearable
                @change="deptChange"
                placeholder="请选择"
                :options="controlData.deptTree"
                :show-all-levels="false"
                :props="{
                        value: 'id',
                        label: 'text',
                        checkStrictly: true
                      }"
              ></el-cascader>-->
              <el-select @change="deptChange" v-model="models.model.departmentId" placeholder="请选择">
                <el-option
                  v-for="item in controlData.deptTree"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="用户等级：" prop="userLevel">
              <el-input v-model="models.model.userLevel" placeholder="用于工作流环节选人顺序"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row>
          <el-col :span="12">
            <el-form-item label="启用账号：" prop="isEnabled">
              <el-radio v-model="models.model.isEnabled" :label="true">是</el-radio>
              <el-radio v-model="models.model.isEnabled" :label="false">否</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="锁定账号：" prop="isLocked">
              <el-radio v-model="models.model.isLocked" :label="true">是</el-radio>
              <el-radio v-model="models.model.isLocked" :label="false">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>-->
      </el-form>
    </template>
    <template v-else-if="active==1">
      <el-form
        style="margin-top: 30px;"
        ref="personInfoForm"
        :model="models.profile"
        :rules="rules.personInfo"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别：" prop="gender">
              <el-radio v-model="models.profile.gender" :label="0">男</el-radio>
              <el-radio v-model="models.profile.gender" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="手机号码：" prop="mobile">
              <el-input v-model="models.profile.mobile"></el-input>
            </el-form-item>
            <el-form-item label="电子邮箱：" prop="email">
              <el-input v-model="models.profile.email"></el-input>
            </el-form-item>
            <el-form-item label="工号：" prop="wkNo">
              <el-input v-model="models.profile.wkNo"></el-input>
            </el-form-item>
            <el-form-item label="门禁号：" prop="employeeNo">
              <el-input v-model="models.profile.employeeNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="8" style="text-align: center;">
                个人图像：
                <br />(jpg格式，2M以内)
              </el-col>
              <el-col :span="16">
                <el-upload
                  class="avatar-uploader"
                  :action="getUploadUrl(models.profile.photoUrl)"
                  :show-file-list="false"
                  :on-success="(res, file, fileList) =>handleAvatarSuccess(res, models)"
                  :before-upload="beforeAvatarUpload"
                >
                  <img
                    style="border: 1px dashed #ccc;border-radius: 6px;"
                    v-if="models.profile.photoUrl"
                    :src="getDownloadUrl(models.profile.photoUrl)"
                    class="avatar"
                  />
                  <i
                    v-else
                    class="el-icon-plus avatar-uploader-icon"
                    style="border: 1px dashed #ccc; border-radius: 6px;"
                  ></i>
                </el-upload>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号码：" prop="cardId">
              <el-input v-model="models.profile.cardId"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期：" prop="birthday">
              <el-date-picker
                v-model="models.profile.birthday"
                type="date"
                default-value="1980-01-01"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="任职职位：" prop="position">
              <el-input v-model="models.profile.position"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="入职日期：" prop="joinDate">
              <el-date-picker
                v-model="models.profile.joinDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="任职状态：" prop="employmentStatus">
              <el-select v-model="models.profile.employmentStatus" placeholder="请选择">
                <el-option
                  v-for="item in controlData.employmentOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转正日期：" prop="confirmationDate">
              <el-date-picker
                v-model="models.profile.confirmationDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="职级：" prop="level">
              <el-select v-model="models.profile.level" placeholder="请选择">
                <el-option
                  v-for="item in controlData.levelOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：" prop="status">
              <el-select v-model="models.profile.status" placeholder="请选择">
                <el-option
                  v-for="item in controlData.profileStatus"
                  :key="item.key"
                  :label="item.key"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="民族：" prop="nation">
              <el-input v-model="models.profile.nation" placeholder="请输入民族"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="户籍类型：" prop="householdType">
              <el-select v-model="models.profile.householdType" placeholder="请选择">
                <el-option
                  v-for="item in controlData.householdTypes"
                  :key="item.key"
                  :label="item.key"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="毕业时间：" prop="graduationTime">
              <el-date-picker
                type="date"
                v-model="models.profile.graduationTime"
                placeholder="请选择毕业时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称证书：" prop="vocationalCert">
              <el-input v-model="models.profile.vocationalCert" placeholder="请输入职称证书"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急联系人：" prop="emergencyContact">
              <el-input v-model="models.profile.emergencyContact" placeholder="请输入紧急联系人"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系：" prop="emergencyContactRelation">
              <el-input v-model="models.profile.emergencyContactRelation" placeholder="请输入紧急联系人关系"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号：" prop="emergencyContactMobile">
              <el-input v-model="models.profile.emergencyContactMobile" placeholder="请输入紧急联系人手机号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯：" prop="nativePlace">
              <el-input v-model="models.profile.nativePlace" placeholder="请输入籍贯"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="婚姻状况：" prop="maritalStatus">
              <el-select v-model="models.profile.maritalStatus" placeholder="请选择">
                <el-option label="未婚" value="UNMARRIED"></el-option>
                <el-option label="已婚" value="MARRIED"></el-option>
                <el-option label="离异" value="DIVORCE"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="政治面貌：" prop="politicalStatus">
              <el-select v-model="models.profile.politicalStatus" placeholder="请选择">
                <el-option label="群众" value="MASSES"></el-option>
                <el-option label="团员" value="LEAGUE_MEMBER"></el-option>
                <el-option label="党员" value="PARTY_MEMBER"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="银行帐号：" prop="bankAccount">
              <el-input v-model="models.profile.bankAccount" placeholder="请输入银行帐号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历：" prop="education">
              <el-select v-model="models.profile.education" placeholder="请选择">
                <el-option label="博士" value="DOCTOR"></el-option>
                <el-option label="硕士" value="MASTER"></el-option>
                <el-option label="本科" value="UNDERGRADUATE"></el-option>
                <el-option label="大专" value="JUNIOR"></el-option>
                <el-option label="高中" value="SENIOR"></el-option>
                <el-option label="中专" value="SPECIAL"></el-option>
                <el-option label="初中" value="MIDDLE"></el-option>
                <el-option label="小学" value="PRIMARY"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="毕业院校：" prop="school">
              <el-input v-model="models.profile.school" placeholder="请输入毕业院校"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业：" prop="speciality">
              <el-input v-model="models.profile.speciality" placeholder="请输入专业"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系地址：" prop="address">
              <el-input v-model="models.profile.address"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="户口地址：" prop="originalAddress">
              <el-input v-model="models.profile.originalAddress"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注：" prop="memo">
              <el-input type="textarea" v-model="models.profile.memo" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-else-if="active==2">
      <el-row style="margin-top: 30px;">
        <el-col :span="12" :offset="6">
          <el-alert title="请分配岗位(可多选),非必填(普通员工无需选择)" type="success" :closable="false"></el-alert>
          <el-select no-data-text="请先在账号信息中选择部门！" v-model="posts" multiple placeholder="请选择">
            <el-option
              v-for="item in postoptions"
              :key="item.positionId"
              :label="item.name"
              :value="item.positionId"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="padding-top:20px">
        <el-col :span="12" :offset="6">
          <el-alert title="请分配角色(可多选)" type="warning" :closable="false"></el-alert>
          <el-select v-model="roles" multiple placeholder="请选择">
            <el-option
              v-for="item in rolesoptions"
              :key="item.roleId"
              :label="item.name"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
    </template>
    <template v-else>
      <el-row>
        <el-col :span="12" :offset="6">
          <el-alert title="请分配系统(可多选)" type="success" :closable="false"></el-alert>
          <el-select v-model="systems" multiple placeholder="请选择">
            <el-option
              v-for="item in systemoptions"
              :key="item.systemId"
              :label="item.systemName"
              :value="item.systemId"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-alert
        style="margin-top: 20px;"
        title="创建用户成功之后,会将账号、密码信息发送至指定邮箱喔！"
        type="info"
        :closable="false"
      ></el-alert>
    </template>
    <el-divider>
      <el-button type="info" :hidden="createC" style="margin-top: 12px;" @click="back">上一步</el-button>
      <el-button type="primary" :hidden="createA" style="margin-top: 12px;" @click="next">下一步</el-button>
      <el-button type="success" :hidden="createB" style="margin-top: 12px;" @click="submit">创建用户</el-button>
    </el-divider>
  </div>
</template>
<script>
import _ from "lodash";
import request from "@/utils/request";
export default {
  components: {},
  data() {
    return {
      active: 0,
      models: {
        model: {},
        profile: {},
      },
      controlData: {},
      rules: {
        userInfo: {
          userName: [
            {
              required: true,
              message: "请输入名称(2-4个中文字符)",
              trigger: "blur",
              pattern: /^[\u4e00-\u9fa5]{2,4}$/, //2-4个中文字符正则
            },
          ],
          loginId: [
            {
              required: true,
              message: "请输入登录账号(4-15个英文字符)",
              trigger: "blur",
              pattern: /^[a-zA-Z]{4,15}$/,
            },
          ],
          departmentId: [
            {
              required: true,
              message: "请选择部门",
              trigger: "change",
            },
          ],
          //   password: [
          //     {
          //       required: true,
          //       message:
          //         "密码必须同时由字母、数字、特殊符号(不包括_)等8位以上字符组成。",
          //       pattern:
          //         /([a-zA-z]+\d+\S*\W+\S*)|(\d+[a-zA-z]+\S*\W+\S*)|(\d+\W+\S*[a-zA-z]+\S*)|([a-zA-z]+\W+\S*\d+\S*)|(\W+[a-zA-z]+\S*\d+\S*)|(\W+\d+\S*[a-zA-z]+\ S*)/,
          //       trigger: "blur",
          //     },
          //   ],
          //   checkPass: [{ required: true, message: " " }],
        },
        personInfo: {
          mobile: [
            {
              required: true,
              message: "请输入正确的手机号",
              trigger: ["blur", "change"],
              pattern:
                /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            },
          ],
          email: [
            { required: true, message: "请输入邮箱地址", trigger: "blur" },
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"],
            },
          ],
          gender: { required: true, message: "请选择性别", trigger: "change" },
          employeeNo: [
            { required: true, message: "请输入门禁号", trigger: "blur" },
          ],
          position: [
            { required: true, message: "请输入任职职位", trigger: "blur" },
          ],
          joinDate: [
            { required: true, message: "请选择入职日期", trigger: "change" },
          ],
          employmentStatus: [
            { required: true, message: "请选择任职状态", trigger: "change" },
          ],
          level: [{ required: true, message: "请分配职级", trigger: "change" }],
        },
      },
      //岗位
      posts: [],
      postoptions: [],
      //角色
      roles: [],
      rolesoptions: [],
      //系统
      systems: [],
      systemoptions: [],
      createB: true,
      createA: false,
      createC: true,
    };
  },
  created() {
    this.initData();
  },
  methods: {
    submit() {
      if (this.systems.length == 0) {
        this.$message.info("请至少分配一个系统资源喔。");
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: "正在为系统创建用户...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      var systems = _.join(this.systems, ",");
      var posts = _.join(this.posts, ",");
      var roles = _.join(this.roles, ",");
      request({
        url: "/eip/register/createUser",
        method: "post",
        data: {
          posts: posts,
          roles: roles,
          systems: systems,
          model: this.models.model,
          profile: this.models.profile,
        },
      })
        .then((r) => {
          if (r && !r.initMessage) {
            loading.close();
            if (r.success) {
              this.$message({
                message: "创建用户成功！",
                type: "success",
              });
              this.$root.closeModal("/eip/sysUser/addUser");
            } else {
              this.$message.error(r.message);
            }
          } else {
            this.$message.error(r.initMessage || "数据请求失败");
          }
        })
        .catch((e) => {
          reject(e);
        });
    },
    deptChange(val) {
      this.postoptions = [];
      request({
        url: "/admin/sysPosition/getPositions",
        method: "get",
        params: {
          deptId: val,
        },
      })
        .then((r) => {
          if (r && !r.initMessage) {
            this.postoptions = r.data;
          }
        })
        .catch((e) => {
          reject(e);
        });
    },
    initData() {
      request({
        url: "/admin/sysUser/getEntity",
        method: "post",
        data: {
          pageAction: "create",
        },
      })
        .then((r) => {
          if (r && !r.initMessage) {
            const { controlData, models } = r;
            this.model = models.model;
            this.controlData = controlData;
          } else {
            this.$message.error(r.initMessage || "数据请求失败");
          }
        })
        .catch((e) => {
          reject(e);
        });
      request({
        url: "/admin/sysRole/getRoles",
        method: "get",
      })
        .then((r) => {
          if (r && !r.initMessage) {
            this.rolesoptions = r.data;
          }
        })
        .catch((e) => {
          reject(e);
        });
      request({
        url: "/sso/ssoSystem/getSsoSystems",
        method: "get",
      })
        .then((r) => {
          if (r && !r.initMessage) {
            this.systemoptions = r.data;
          }
        })
        .catch((e) => {
          reject(e);
        });
    },
    beforeAvatarUpload(file) {
      // 控制上传的大小及格式
      // ie不支持const let
      /*const isJPG = file.type === 'image/jpeg';
                    const isLt2M = file.size / 1024 / 1024 < 2;*/
      let isJPG = file.type === "image/jpeg";
      let isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    back() {
      this.active--;
      if (this.active == 0) {
        this.createC = true;
        this.createA = false;
        this.createB = true;
        return;
      } else {
        this.createC = false;
        this.createA = false;
        this.createB = true;
        return;
      }
    },
    next() {
      if (this.active == 0) {
        this.$refs["userInfoForm"].validate((valid) => {
          if (valid) {
            this.active++;
            this.createC = false;
          } else {
            this.$message.info("请完善账号信息");
          }
        });
        return;
      }
      if (this.active == 1) {
        this.$refs["personInfoForm"].validate((valid) => {
          if (valid) {
            this.active++;
            this.createC = false;
          } else {
            this.$message.info("请完善个人信息");
          }
        });
        return;
      }
      if (this.active == 2) {
        if (this.roles.length > 0) {
          this.active++;
          this.createC = false;
          this.createB = false;
          this.createA = true;
        } else {
          this.$message.info("请分配至少一个角色！");
        }
        return;
      }
    },
    getEntity() {},
    getUploadUrl(attachmentId) {
      return `${
        process.env.VUE_APP_BASE_API
      }/attachment/upload?type=picture&attachmentId=${
        attachmentId || ""
      }&isTemp=${!attachmentId}`;
    },
    getDownloadUrl(attachmentId) {
      return `${
        process.env.VUE_APP_BASE_API
      }/attachment/download?attachmentId=${attachmentId}&rnd=${Math.random()}`;
    },
    handleAvatarSuccess(res, models) {
      this.$set(this.models.profile, "photoUrl", res.attachmentId);
    },
  },
};
</script>

<style scoped lang="scss">
.avatar-uploader {
  padding-bottom: 5px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  line-height: 160px;
  text-align: center;
}
.avatar {
  width: 160px;
  height: 160px;
  display: block;
}
</style>

